package com.powernode.service.impl;

import com.powernode.domain.Goods;
import com.powernode.domain.Order;
import com.powernode.mapper.GoodsMapper;
import com.powernode.mapper.OrderMapper;
import com.powernode.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
public class GoodsServiceImpl implements GoodsService {

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 常规方案: 锁加载调用的方法的地方要加载事务外面
     * @param userId
     * @param goodsId
     */
    @Override
    @Transactional(rollbackFor = Exception.class)   // 事务隔离级别: 可重复读(rr)
    public void realSeckill(int userId, int goodsId) {
        Goods goods = goodsMapper.selectByPrimaryKey(goodsId);
        int finalStock = goods.getTotalStocks() - 1;
        if (finalStock < 0) {
            throw new RuntimeException("商品: " + goodsId + "库存不足,用户id为: " + userId);
        }

        goods.setTotalStocks(finalStock);
        goods.setUpdateTime(new Date());
        int i = goodsMapper.updateByPrimaryKey(goods);
        if (i > 0) {
            Order order = new Order();
            order.setGoodsid(goodsId);
            order.setUserid(userId);
            order.setCreatetime(new Date());
            orderMapper.insert(order);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void realSeckill1(int userId, int goodsId) {
        // update goods set total_stocks = total_stocks - 1, update_time = now() where goods_id = #{goodsId}
        int i = goodsMapper.updateStock(goodsId);
        if (i > 0) {
            Order order = new Order();
            order.setGoodsid(goodsId);
            order.setUserid(userId);
            order.setCreatetime(new Date());
            orderMapper.insert(order);
        }
    }
}
